/*!
 * =====================================================
 * RFQ v1.0.0 ()
 * jake.xu
 * 18616016103@163.com
 * =====================================================
 */

window.RFQ = {
    version: '1.0'
};


/******简单封装对象********/
(function($, rfq) {
    $.extend(rfq, {
        error: function(msg) {
            //alert(msg);
            $.zui.messager.show(msg, {placement: 'center', type: 'danger', icon: 'icon-exclamation-sign'});
        },
        info:function(msg){
            //alert(msg);
            $.zui.messager.show(msg, {placement: 'center', type: 'danger', icon: 'icon-exclamation-sign'});
        },
        warn:function(msg){
            //alert(msg);
            $.zui.messager.show(msg, {placement: 'center', type: 'danger', icon: 'icon-exclamation-sign'});
        },
        prompt: function(msg, title, callback) {
            var msg = prompt(msg, title);
            callback && callback(msg);
        },
        confirm: function(msg,callback) {
            if(!confirm(msg)) return;
            callback && callback();
        },
        //d: Function.prototype.bind.call(console.debug, console),
        d: function (info) {
            //window.console && console.log(info);
        },
        decodeRegexp: /\+/g,
        paramRegexp: /([^&=]+)=?([^&]*)/g,
        decode: function(a) {
            return decodeURIComponent(a.replace(this.decodeRegexp, " "))
        },
        parseParams: function(a) {
            var b = {};
            if (a = a && (0 === a.indexOf("?") ? a.replace("?", "") : a))
                for (var c; c = this.paramRegexp.exec(a);) b[this.decode(c[1])] = this.decode(c[2]);
            return b;
        },
        showWaiting: function() {},
        closeWaiting: function() {},
        clearFileInput: function (fileEl) {
            /*fileEl = $(fileEl).next()[0];*/
            if (fileEl.outerHTML) {
                fileEl.outerHTML = fileEl.outerHTML;
            } else {
                fileEl.value = "";
            }
        },
        formatTax: function (tax) {
            return (+tax).toFixed(0) + '%';
        },
        formatPercent: function (num1,num2) {
            return (Math.round(parseFloat(num1) / parseFloat(num2) * 10000) / 100.00 + "%");
        },
        scaleCheck:function(el,scale){
            var valTmp =  el.value;
            var num = +valTmp;
            if($(el).data('name') != 'tax') {
                if(num != 0 && !num){
                    RFQ.error('请输入数字');
                    el.value = '';
                }else  if(scale == 0){
                    //临时处理
                    /*if($(el).data('name') == 'tax'){
                     if(!/^\d{0,2}$/.test(valTmp)){
                     RFQ.error('只能输入1-2位整数');
                     el.value = valTmp.substr(0,2);
                     }
                     }*/
                }else if(~valTmp.indexOf('.') && valTmp.split('\.')[1].length > scale){
                    RFQ.error('小数部分输入太长，应该小于等于'+scale+'位');
                    el.value = num.toFixed(scale);
                }
            }
        },
        scaleChecks:function(el,scale){
            var valTmp =  el.value;
            var num = +valTmp;
            if($(el).data('name') != 'tax') {
                if(num != 0 && !num){
                    RFQ.error('请输入数字');
                    el.value = '';
                }else  if(scale == 0){
                    //临时处理
                    /*if($(el).data('name') == 'tax'){
                     if(!/^\d{0,2}$/.test(valTmp)){
                     RFQ.error('只能输入1-2位整数');
                     el.value = valTmp.substr(0,2);
                     }
                     }*/
                }else if(~valTmp.indexOf('.') && valTmp.split('\.')[1].length > scale){
                    RFQ.error('小数部分输入太长，应该小于等于'+scale+'位');
                    if(scale === 2){
                        el.value = Number(num.toString().match(/^\d+(?:\.\d{0,2})?/));
                    }
                    if(scale === 4){
                        el.value = Number(num.toString().match(/^\d+(?:\.\d{0,4})?/));
                    }
                }
            }
        }
    });

    /*********开始初始化**************/
    rfq.Init = function(page){
        this.initPage(page);
    };
    $.extend(rfq.Init.prototype,{
        initPage: function(page) {
            this.initConfig();
            this.initEvent();
            this.initHook();
            if($ && page){
                window.page = new rfq[page + "Page"];
            }
        },
        initConfig: function(c) {
            rfq.Init = this;
        },
        initEvent: function() {
            var that = this;
        },
        initHook: function () {
            //初始化相关钩子
            //下拉选项钩子
            $('select[aria-valuenow]').each(function () {
                var $this = $(this);
                $this.val($this.attr('aria-valuenow'));
            });
            //时间钩子

        }
    });
})(window.jQuery, window.RFQ);


/******zui下的提示封装********/
(function($, rfq) {
    $.zui && $.extend(rfq,{
        error: function(msg) {
            $.zui.messager.show(msg, {placement: 'center', type: 'danger', icon: 'icon-exclamation-sign'});
        },
        info:function(msg){
            $.zui.messager.show(msg, {placement: 'center', type: 'success', icon: 'icon-ok-sign'});
        },
        warn:function(msg){
            $.zui.messager.show(msg, {placement: 'center', type: 'warning', icon: 'icon-warning-sign'});
        },
        confirm: function(title,msg,callback) {
            if(!callback){
                callback = msg;
                msg = title;
                title = '系统提示';
            }
            var $modal = $('#myModal');
            if(!$modal[0]){
                var modalHTML = [];
                modalHTML.push('<div class="modal fade">');
                modalHTML.push('    <div class="modal-dialog">');
                modalHTML.push('    <div class="modal-content">');
                modalHTML.push('    <div class="modal-header">');
                modalHTML.push('    <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">关闭</span></button>');
                modalHTML.push('    <h4 class="modal-title"></h4>');
                modalHTML.push('    </div>');
                modalHTML.push('    <div class="modal-body">');
                modalHTML.push('    <p></p>');
                modalHTML.push('    </div>');
                modalHTML.push('   <div class="modal-footer">');
                modalHTML.push('    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>');
                modalHTML.push('    <button type="button" class="btn btn-primary js-confirm">确认</button>');
                modalHTML.push('    </div>');
                modalHTML.push('    </div>');
                modalHTML.push('    </div>');
                modalHTML.push('</div>');
                $modal = $(modalHTML.join(''));
                $('body').append($modal);
            }
            $modal.find('.modal-title').html(title||'系统提示');
            $modal.find('.modal-body p').html(msg);
            $modal.find('.js-confirm').off('click').on('click', function () {
                callback && callback();
                $modal.modal('toggle');
            });
            $modal.modal('toggle');
        }
    });
})(window.jQuery, window.RFQ);


/******
 * jqGrid api 简单封装
 * 扩展参数 autoLoad  true 首次加载在 false 默认不加载数据 maxHeight最大高度
 * 扩展参数 singleSelect 单选框效果
 * 扩展方法 reload  手动加载数据
 * ********/
(function($, rfq) {
    var defaultJqGridOptions = {
        datatype: 'json',
        mtype: 'POST',
        rownumbers: true,
        autowidth:true,
        colModel: [],
        jsonReader: { //映射server端返回的字段
            root: "list",
            rows: "list",
            page: "pageNum",
            total: "pages",
            records: "total"
        },
        prmNames: {
            id: 'id'//请求参数映射，如默认参数为id，实际参数为myId则可在此映射
        },
        viewrecords: true, // show the current page, data rang and total records on the toolbar
        width: 870,
        height: "100%",
        rowNum: 10,
        rowList: [10, 20, 30],
        sortname: 'id',
        sortorder: 'asc'
    };
    var jqGridCache = {};
    rfq.jqGrid = function(seletor){
        if(jqGridCache[seletor]){
            return jqGridCache[seletor];
        }
        if(this === rfq){
            return new rfq.jqGrid(seletor);
        }
        this.jqObj = $(seletor);
        this.selectRowid = -1;
        this.selectRowState = false;
        jqGridCache[seletor] = this;
        return this;
    };
    $.extend(rfq.jqGrid.prototype,{
        init: function(options) {
            var that = this;
            options = options||{};
            if(options.autoLoad === false){
                options.datatype = 'local';
            }
            var newOptions = $.extend({},defaultJqGridOptions,options);
            if(newOptions.singleSelect){
                newOptions.multiselect = true;
                newOptions.onSelectRow = function (rowid,status) {
                    RFQ.d(that.selectRowid);
                    RFQ.d(status);
                    if(rowid != that.selectRowid && that.selectRowState){
                        that.jqObj.jqGrid('setSelection',that.selectRowid,false);
                    }
                    that.selectRowid = rowid;
                    that.selectRowState = status;
                };
            }
            that.jqObj.jqGrid(newOptions);
            if(newOptions.rownumbers){
                that.jqObj.jqGrid('setLabel', 0,'序号');
            }
            if(newOptions.maxHeight){
                that.jqObj.closest(".ui-jqgrid-bdiv").css({ 'maxHeight' : newOptions.maxHeight });
            }
            if(newOptions.singleSelect){
                $('#'+that.jqObj[0].id+'_cb').find(':checkbox').hide();
            }
            return this;
        },
        reload:function(options){
            options = options||{};
            if(!options.postData){
                options = {postData:options};
            }
            options = $.extend({datatype:'json',page:1},options);
            this.selectRowid = -1;
            this.selectRowState = false;
            RFQ.d(options);
            this.jqObj.jqGrid('setGridParam',options).trigger('reloadGrid');
        },
        loadLocal: function (data) {
            this.jqObj.jqGrid("clearGridData");
            this.jqObj.jqGrid('setGridParam',{datatype:'local',data:data}).trigger('reloadGrid');
        },
        resize:function(){//重新触发布局，防止显示为空白的BUG
            this.jqObj.jqGrid('resizeGrid');
        },
        resetSelection:function(){//重新触发布局，防止显示为空白的BUG
            this.selectRowid = -1;
            this.selectRowState = false;
            this.jqObj.jqGrid('resetSelection');
        }
    });
})(window.jQuery, window.RFQ);


/******
 * ajaxSubmit api 简单封装
 * 增加 js-block 钩子
 * 表单的按钮加入.js-block 类 ，表单提价时会自动将按钮置为不可用，一旦服务器响应，按钮可用
 * ********/
(function($, rfq) {
    var defaultAjaxSubmitOptions = {
        type: 'post', // 表单默认提交方式
        dataType: 'json'
    };
    var ajaxSubmitCache = {};
    rfq.form = function(seletor){
        if(ajaxSubmitCache[seletor]){
            return ajaxSubmitCache[seletor];
        }
        if(this === rfq){
            return new rfq.form(seletor);
        }
        this.jqObj = $(seletor);
        this.blockBtn = this.jqObj.find('.js-block');
        ajaxSubmitCache[seletor] = this;
        return this;
    };
    $.extend(rfq.form.prototype,{
        ajaxSubmit: function(url,data,callback) {
            var jqObj = this.jqObj;
            var blockBtn =  this.blockBtn;
            //按钮不可用
            blockBtn.attr('disabled','disabled');
            var newOptions = $.extend({},defaultAjaxSubmitOptions);
            newOptions.url = url;
            newOptions.data = data;
            newOptions.success = function (data) {
                blockBtn.removeAttr('disabled');
                if(data.rspcod != 200){
                    RFQ.error(data.rspmsg);
                    return;
                }
                callback && callback.call(null,data);
            };
            newOptions.error = function(XmlHttpRequest, textStatus, errorThrown){
                blockBtn.removeAttr('disabled');
                var responseText = XmlHttpRequest.responseText;
                if(responseText && ~responseText.indexOf('<head>')){
                    RFQ.error('操作失败！');
                }else{
                    RFQ.error('网络异常，请联系管理员！');
                }
            };
            this.jqObj.ajaxSubmit(newOptions);
            return this;
        }
    });
})(window.jQuery, window.RFQ);

/******
 * ajax 请求封装 取代jquery post get 方法
 * 统一请求参数，包括超时，缓存等
 * 统一前置操作 包括按钮置灰等
 * 统一loading
 * ********/
(function($, rfq) {
    var defaultAjaxOptions = {
        timeout: 15000,
        async: true,
        type:'post',
        //cache:false,
        dataType:'json',
        beforeSend:function(){},
        complete:function(){},
        success:function(){},
        error:function(){}
    };

    $.extend(rfq,{
        ajax: function(options) {
            options = $.extend({},defaultAjaxOptions,options);
            $.ajax(options);
        },
        post:function(url,data,callback,async){
            if(async === false){
                var options = {async:false,url:url,data:data};
                options.success = function(msg){
                    if(msg.rspcod != 200){
                        RFQ.error(msg.rspmsg||'网络异常！');
                        return;
                    }
                    callback && callback.call(null,msg);
                };
                this.ajax(options);
            }else{
                $.post(url,data,function(msg){
                    if(msg.rspcod != 200){
                        RFQ.error(msg.rspmsg||'网络异常！');
                        return;
                    }
                    callback && callback.call(null,msg);
                });
            }
        },
        get:function(url,data,callback){
            $.get(url,data,function(msg){
                if(msg.rspcod != 200){
                    RFQ.error(msg.rspmsg);
                    return;
                }
                callback && callback.call(null,msg);
            });
        }
    });
})(window.jQuery, window.RFQ);

/********扩展方法**********/
(function($, rfq) {
    String.prototype.toDate = function (format) {
        var regex = format.replace(/yyyy/, '([0-9]{4})').replace(/yy/, '([0-9]{2})')
            .replace(/y/, '([0-9]{1,2})').replace(/MM/, '([0-9]{2})')
            .replace(/dd/, '([0-9]{2})').replace(/M/, '([0-9]{1,2})')
            .replace(/d/, '([0-9]{1,2})').replace(/HH/, '([0-9]{2}|0)')
            .replace(/mm/, '([0-9]{2})').replace(/ss/, '([0-9]{2})')
            .replace(/H/, '([0-9]{1,2})').replace(/m/, '([0-9]{1,2})')
            .replace(/s/, '([0-9]{1,2})');

        var matchs = this.match(new RegExp('^' + regex + '(.*)'));

        if (!matchs || matchs.length <= 0) //return null;
            throw ('String.toFormatDate("' + format + '") format error');

        var formatIndex = format.replace(/y+/, 'y').replace(/M+/, 'M').replace(/d+/, 'd')
            .replace(/H+/, 'H').replace(/m+/, 'm').replace(/s+/, 's')
            .replace(/[^a-z]+/ig, '');

        var date = { y: 0, M: 0, d: 0, H: 0, m: 0, s: 0 };
        for (var i = 0; i < formatIndex.length; i++) {
            var v = parseInt(matchs[i + 1], 10);
            if (isNaN(v))
                return null;
            date[formatIndex.substr(i, 1)] = v;
        }

        var ss = new Date();

        var s = new Date(date.y, date.M - 1, date.d, date.H, date.m, date.s);
        return new Date(date.y, date.M - 1, date.d, date.H, date.m, date.s);
    }

    /// <summary>
    /// 左侧字符填充
    /// </summary>
    /// <param name="ch">填充字符</param>
    /// <param name="length">填充后字符串长度</param>
    /// <returns>填充后字符串</returns>
    String.prototype.padLeft = function(ch, length) {
        var str = this;
        for(var i=0;i<length - this.length; i++)
            str = ch + str;
        return str;
    }

    /// <summary>
    /// 右侧字符填充
    /// </summary>
    /// <param name="ch">填充字符</param>
    /// <param name="length">填充后字符串长度</param>
    /// <returns>填充后字符串</returns>
    String.prototype.padRight = function(ch, length) {
        var str = this;
        for(var i=0; i<length - str.length; i++)
            str = str + ch;
        return str;
    }

    /// <summary>
    /// 时间格式化
    /// </summary>
    /// <param name="format">yyyy-MM-dd</param>
    /// <returns>格式化后的字符串</returns>
    //Date.prototype.toString = function (format) {
    //    if (!format || typeof format != 'string')
    //        format = "yyyy-MM-dd";
    //
    //    format = format.replace(/yyyy/, this.getFullYear())
    //        .replace(/yy/, this.getFullYear().toString().substring(2))
    //        .replace(/y/, this.getFullYear().toString().substring(2).trimLeft("0"))
    //        .replace(/MM/, (this.getMonth() + 1).toString().padLeft('0', 2))
    //        .replace(/dd/, this.getDate().toString().padLeft('0', 2))
    //        .replace(/M/, (this.getMonth() + 1))
    //        .replace(/d/, this.getDate().toString())
    //        .replace(/HH/, this.getHours().toString().padLeft('0', 2))
    //        .replace(/mm/, this.getMinutes().toString().padLeft('0', 2))
    //        .replace(/ss/, this.getSeconds().toString().padLeft('0', 2))
    //        .replace(/H/, this.getHours())
    //        .replace(/m/, this.getMinutes())
    //        .replace(/s/, this.getSeconds());
    //    date = null;
    //    return format;
    //}

    //简单的模板封装调用
    String.prototype.format = function(args) {
        var result = this;
        if (arguments.length > 0) {
            if (arguments.length == 1 && typeof (args) == "object") {
                for (var key in args) {
                    if(args[key]!=undefined){
                        var reg = new RegExp("({" + key + "})", "g");
                        result = result.replace(reg, args[key]);
                    }
                }
            }
            else {
                for (var i = 0; i < arguments.length; i++) {
                    if (arguments[i] != undefined) {
                        var reg= new RegExp("({)" + i + "(})", "g");
                        result = result.replace(reg, arguments[i]);
                    }
                }
            }
        }
        return result;
    }

    //文本而简单替换
    rfq.renderText = function(seletor,data){
        var $container = $(seletor);
        $container.find('[data-mp]').each(function(){
            var $this = $(this);
            var mp = $this.data('mp');
            $this.html(data[mp]||'');
        });
    }

    /**
     * 解析base64数据
     * * @param {Object} data
     */
    rfq.parseBase64Data = function(data){
        var rval = {};
        if(data){
            var data = data.split(',');
            rval.file = data.pop();
            rval.type = data[0].split('/').pop().substr(0,3);
        }
        return rval;
    };

    /**
     * 脚本新窗口打开连接，防止被浏览器阻止
     * * @param {Object} data
     */
    rfq.openLinkInBlank = function (url) {
        var $mockForm = $('_openWin');
        if(!$mockForm[0]){
            $mockForm = $('<form id="_openWin" action="" target="_blank" method="get" style="display: none"></form>');
            $('body').append($mockForm);
        }
        $mockForm.attr('action',url);
        RFQ.d(url);
        $mockForm[0].submit();
    };

})(window.jQuery, window.RFQ);

/**
 * 初始化
 */
$(function () {
    new RFQ.Init();
});

//下载、打印询价单
(function(){
    //打印
    window.requestPrint = function(){
        RFQ.post(ctx+'/rfqRequest/requestPrint',null,function(data){
            RFQ.info("该功能尚未实现");
        });
    };
    //下载
    window.requestDownload = function(){
        RFQ.post(ctx+'/rfqRequest/requestDownload',null,function(data){
            RFQ.info("该功能尚未实现");
        });
    };
    window.dacDownload = function(requestId,biddingMethod,qtype){
        $.post(ctx+"/rfqRequestItem/exportRecord2",{requestId: requestId,biddingMethod:biddingMethod,qtype:qtype},function(data){
            //console.log(data);
            if ("success"==data.status) {
                RFQ.info('明细清单下载成功！');
            } else {
                RFQ.error(data.message);
            };
        });
    };

})();

//编辑器字数2000字校验
(function(){
    /**
     * @param $id
     * @returns {boolean} true 验证通过 false 验证失败
     */
    window.validate2000 = function($id){
        var str = $id.text();
        var format_str =  str.split('&lt;').join('<').split('&gt;').join('>').replace(/\s+/g, "");
        var len = format_str.length;
        if (len > 2000 ) {
            return false;
        }
        else {
            return true;
        }
    };

})();